//
//  ShowTableViewController.swift
//  TwitterSearchDemo
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 lanou. All rights reserved.
//

import UIKit

class ShowTableViewController: UITableViewController {
    
    var urlString: String?
    var showArray: [ShowModel] = []
    //设置推特账号
    func setTwitter(str: String)
    {
        let accountStore = ACAccountStore.init()
        let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
        //获取访问账号
        let accountArray = accountStore.accountsWithAccountType(accountType)
        
        accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: { (granted: Bool, error: NSError!) -> Void in
            //授权访问
            if(granted)
            {
                //如果添加了账号
                
                if accountArray == nil
                {
                    print("账号为空")
                    return
                }
                if accountArray.count > 0
                {
                    let request = SLRequest.init(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: NSURL(string: str), parameters: nil)
                    request.account = accountArray[0] as! ACAccount
                    request.performRequestWithHandler({ (data: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) -> Void in
                        if (200 == urlResponse.statusCode) {
                            do {
                                let rootDic : NSDictionary
                                try rootDic = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                                let statusesArr = rootDic["statuses"] as! NSArray
                                for dic in statusesArr
                                {
                                    let showModel = ShowModel()
                                    showModel.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
                                    self.showArray.append(showModel)

                                }      
                                
                            }
                            catch let error as NSError {
                                print(error)
                            }
                            
                            NSNotificationCenter.defaultCenter().postNotificationName("reload", object: nil)
                        } else  {
                            print("发布信息失败，错误代码：\(urlResponse.statusCode)")
                        }
                    })
                }
                else {
                    print("没有账号")
                }
            }
            else
            {
                print("未授权")
            }
            
        })
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setTwitter(self.urlString!)
        
        self.tableView.registerClass(ShowTableViewCell.classForCoder(), forCellReuseIdentifier: "reuseIdentifier")
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector.init("reload"), name: "reload", object: nil)
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    func reload()
    {
        self.tableView.reloadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.showArray.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: ShowTableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! ShowTableViewCell
        let showModel = self.showArray[indexPath.row]
        cell.articleLabel?.text = showModel.text!
        cell.nameLabel?.text = showModel.name!
        print(showModel.profile_image_url_https!)
        cell.iconView?.setImageWithURL(NSURL(string: showModel.profile_image_url_https!))
        // Configure the cell...

        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 240
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
